import { InjectRepository } from '@nestjs/typeorm';
import { AddressEntity } from './entities/address.entity';
import { Repository } from 'typeorm';
import { CreateAddressDto, UpdateAddressDto } from './dto/address.dto';
import { ResultData } from 'src/common/utils/result';
import { BadRequestException } from '@nestjs/common';
export class AddressService {
  constructor(
    @InjectRepository(AddressEntity)
    private readonly addressRepo: Repository<AddressEntity>,
  ) {}
  async create(userId: number, address: CreateAddressDto) {
    if (address.isDefault) {
      await this.addressRepo.update({ userId }, { isDefault: false });
    }
    await this.addressRepo.save({
      userId,
      ...address,
    });
    return ResultData.ok();
  }

  async findList(userId: number) {
    const addrList = await this.addressRepo.find({ where: { userId } });
    return ResultData.ok(addrList);
  }

  async findDefault(userId: number) {
    const defaultAddress = await this.addressRepo.findOne({
      where: {
        userId,
        isDefault: true,
      },
    });
    return ResultData.ok(defaultAddress);
  }

  async findOne(id: number, userId: number) {
    const addressItem = await this.addressRepo.findOne({
      where: {
        userId,
        id,
      },
    });
    return ResultData.ok(addressItem);
  }

  async update(userId: number, data: UpdateAddressDto) {
    const { id, ...rest } = data;
    const newAddress = {
      ...rest,
      userId,
    };
    await this.addressRepo.update(id, newAddress);
    return ResultData.ok();
  }

  async remove(id: number, userId: number) {
    const address = await this.addressRepo.findOneBy({ id });
    if (address.userId !== userId) {
      throw new BadRequestException('请确保用户一致');
    }
    await this.addressRepo.remove(address);
    return ResultData.ok();
  }
}
